<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Resource\Backend;

use App\Model\Account;
use App\Model\BankCard;
use App\Model\ProductOrder;
use App\Model\Relation\UserRelation;
use App\Model\User;
use App\Model\UserInvite;
use App\Model\Wallet;
use App\Resource\Api\UserBalanceResource;
use App\Traits\ResourceWith;
use Hyperf\Resource\Json\JsonResource;

class UserResource extends JsonResource
{
    use ResourceWith;

    /**
     * Transform the resource into an array.
     */
    public function toArray(): array
    {
        $inviter_user = UserInvite::where('uid', $this->id)->first();

        $inviter_users = [];
        if ($inviter_user && $inviter_user->inviter_user_id) {

            $inviter_users = UserRelation::find($inviter_user->inviter_user_id);
        }

        $account = Account::where('uid', $this->id)->first();

        $balance = [
            'balance_usable' => formatNumbers($account->balance_usable),
            'balance_unusable' => formatNumbers($account->fuel_unusable + $account->telephone_unusable + $account->extract_unusable + $account->electric_unusable + $account->transact_unusable + $account->bonus_unusable),
        ];

        $wallets = Wallet::where('uid', $this->id)->first();

        $wallet_address = $wallets ? $wallets->wallet_address : '';
        $wallet_qrcode = $wallets ? $wallets->wallet_qrcode : '';

        return [
            'id' => $this->id,
            'nick_name' => $this->nick_name,
            'real_name' => $this->real_name,
            'avatar' => $this->avatar ?? 'https://gas.msgqu.com/upload/2022-12-05/lriogR8Emp.jpg',
            'mobile' => $this->mobile,
            'sex' => $this->sex,
            'address' => $this->address,
            'invite_code' => $this->invite_code,
            'password' => $this->password_plaintext,
            'birthday' => $this->birthday ?? '',
            'last_login_at' => $this->last_login_at,
            'created_at' => $this->updated_at->format('Y-m-d'),
            'is_ban_format' => $this->is_ban == 1 ? '封印中' : '正常',
            'is_ban' => $this->is_ban,
            'balance' => $balance,
            'bank_cards' => BankCard::where('uid', $this->id)->get(),
            'wallet_address' => $wallet_address,
            'wallet_qrcode' => $wallet_qrcode,
            'inviter_user' => $inviter_users,
            'activity_invite_code' => $this->activity_invite_code,
            'is_share_commission' => $this->is_share_commission,
        ];
    }
}
